using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;

namespace cb0tServer
{
    class WebServerSettings
    {
        public static bool enabled;
        public static ushort port;
        public static ulong hits;

        public static void SetEnabled(bool _enabled)
        {
            enabled = _enabled;
            Save();
        }

        public static void Load()
        {
            enabled = false;
            port = 80;
            hits = 0;

            if (!File.Exists(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/http.xml")) return;

            try
            {
                FileStream f = new FileStream(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/http.xml", FileMode.Open);
                XmlReader xml = XmlReader.Create(new StreamReader(f));

                xml.MoveToContent();
                xml.ReadSubtree().ReadToFollowing("http");
                xml.ReadToFollowing("details");
                xml.ReadSubtree().ReadToFollowing("enabled");
                enabled = bool.Parse(xml.ReadElementContentAsString());
                xml.ReadToFollowing("port");
                port = ushort.Parse(xml.ReadElementContentAsString());
                xml.ReadToFollowing("sbot");
                hits = BitConverter.ToUInt64(Convert.FromBase64String(xml.ReadElementContentAsString()), 0);

                xml.Close();
                f.Flush();
                f.Close();
            }
            catch { }

            enabled = false;
        }

        public static void Save()
        {
            try
            {
                XmlWriterSettings appearance = new XmlWriterSettings();
                appearance.Indent = true;
                XmlWriter xml = XmlWriter.Create(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/http.xml", appearance);

                xml.WriteStartDocument();
                xml.WriteStartElement("http");
                xml.WriteStartElement("details");
                xml.WriteElementString("enabled", enabled.ToString());
                xml.WriteElementString("port", port.ToString());
                xml.WriteElementString("sbot", Convert.ToBase64String(BitConverter.GetBytes(hits)));
                xml.WriteEndElement();
                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Flush();
                xml.Close();
            }
            catch { }
        }

    }
}
